import puppeteer from 'puppeteer';
import fs from 'fs';

/**
 * 页面检查脚本
 * 功能：获取页面的完整HTML结构和元素信息，用于调试登录问题
 */
const inspectPage = async () => {
  let browser = null;
  
  try {
    console.log('===== 页面检查开始 =====');
    
    // 启动浏览器
    browser = await puppeteer.launch({
      headless: true,
      ignoreHTTPSErrors: true,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--ignore-certificate-errors',
        '--allow-insecure-localhost',
        '--disable-features=IsolateOrigins,site-per-process'
      ]
    });
    
    // 创建新页面
    const page = await browser.newPage();
    
    // 设置视图大小
    await page.setViewport({ width: 1920, height: 1080 });
    
    // 监听页面事件
    page.on('console', msg => console.log('页面控制台:', msg.text()));
    page.on('pageerror', err => console.log('页面错误:', err));
    
    // 导航到目标网站
    console.log('正在导航到 https://sharing.powerone.cn:8921/...');
    await page.goto('https://sharing.powerone.cn:8921/', {
      waitUntil: ['domcontentloaded', 'networkidle0'],
      timeout: 60000
    });
    
    console.log('导航成功，页面标题:', await page.title());
    
    // 等待一段时间让页面完全加载
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    // 保存页面截图
    await page.screenshot({ path: 'full-page.png', fullPage: true });
    console.log('页面截图已保存为full-page.png');
    
    // 获取页面的完整HTML结构
    const html = await page.content();
    
    // 保存HTML到文件（只保存前5000个字符以避免过大）
    fs.writeFileSync('page-html.txt', html.substring(0, 5000) + '\n... 内容已截断 ...');
    console.log('页面HTML（前5000字符）已保存为page-html.txt');
    
    // 检查页面上的所有input元素
    console.log('\n===== 页面上的input元素 =====');
    const inputElements = await page.evaluate(() => {
      const inputs = document.querySelectorAll('input');
      return Array.from(inputs).map(input => ({
        id: input.id,
        name: input.name,
        type: input.type,
        placeholder: input.placeholder,
        className: input.className,
        outerHTML: input.outerHTML.substring(0, 200) // 限制长度
      }));
    });
    
    inputElements.forEach((input, index) => {
      console.log(`Input ${index + 1}:`);
      console.log(`  ID: ${input.id || '无'}`);
      console.log(`  Name: ${input.name || '无'}`);
      console.log(`  Type: ${input.type || '无'}`);
      console.log(`  Placeholder: ${input.placeholder || '无'}`);
      console.log(`  Class: ${input.className || '无'}`);
      console.log(`  HTML: ${input.outerHTML}`);
      console.log('---');
    });
    
    // 检查页面上的所有button元素
    console.log('\n===== 页面上的button元素 =====');
    const buttonElements = await page.evaluate(() => {
      const buttons = document.querySelectorAll('button');
      return Array.from(buttons).map(button => ({
        id: button.id,
        name: button.name,
        type: button.type,
        textContent: button.textContent.trim().substring(0, 50), // 限制长度
        className: button.className,
        outerHTML: button.outerHTML.substring(0, 200) // 限制长度
      }));
    });
    
    buttonElements.forEach((button, index) => {
      console.log(`Button ${index + 1}:`);
      console.log(`  ID: ${button.id || '无'}`);
      console.log(`  Name: ${button.name || '无'}`);
      console.log(`  Type: ${button.type || '无'}`);
      console.log(`  Text: ${button.textContent || '无'}`);
      console.log(`  Class: ${button.className || '无'}`);
      console.log(`  HTML: ${button.outerHTML}`);
      console.log('---');
    });
    
    // 检查是否有iframe
    console.log('\n===== 检查页面上的iframe =====');
    const iframes = await page.evaluate(() => {
      const frames = document.querySelectorAll('iframe');
      return Array.from(frames).map((frame, index) => ({
        index,
        id: frame.id,
        name: frame.name,
        src: frame.src,
        className: frame.className
      }));
    });
    
    if (iframes.length > 0) {
      console.log(`找到 ${iframes.length} 个iframe：`);
      iframes.forEach(iframe => {
        console.log(`  Iframe ${iframe.index + 1}:`);
        console.log(`    ID: ${iframe.id || '无'}`);
        console.log(`    Name: ${iframe.name || '无'}`);
        console.log(`    Src: ${iframe.src || '无'}`);
        console.log(`    Class: ${iframe.className || '无'}`);
      });
    } else {
      console.log('没有找到iframe');
    }
    
    // 尝试查找登录相关的元素
    console.log('\n===== 尝试查找登录相关元素 =====');
    const loginRelatedElements = await page.evaluate(() => {
      const loginKeywords = ['登录', 'login', 'signin', 'username', 'password'];
      const elements = [];
      
      // 搜索包含登录关键字的元素
      const allElements = document.querySelectorAll('div, form');
      allElements.forEach(element => {
        const text = element.textContent.toLowerCase();
        const classText = element.className.toLowerCase();
        
        if (loginKeywords.some(keyword => text.includes(keyword) || classText.includes(keyword))) {
          elements.push({
            tag: element.tagName,
            id: element.id,
            className: element.className,
            textContent: text.substring(0, 100).trim(), // 限制长度
            outerHTML: element.outerHTML.substring(0, 300) // 限制长度
          });
        }
      });
      
      return elements;
    });
    
    if (loginRelatedElements.length > 0) {
      console.log(`找到 ${loginRelatedElements.length} 个可能与登录相关的元素：`);
      loginRelatedElements.forEach((element, index) => {
        console.log(`  Element ${index + 1} (${element.tag}):`);
        console.log(`    ID: ${element.id || '无'}`);
        console.log(`    Class: ${element.className || '无'}`);
        console.log(`    Text: ${element.textContent || '无'}`);
        console.log(`    HTML: ${element.outerHTML}`);
        console.log('---');
      });
    } else {
      console.log('没有找到明显的登录相关元素');
    }
    
    console.log('===== 页面检查结束 =====');
    
  } catch (error) {
    console.error('❌ 检查过程中发生错误:', error.message);
    console.error('详细错误信息:', error);
  } finally {
    if (browser) {
      await browser.close();
      console.log('浏览器已关闭');
    }
  }
};

// 执行检查
inspectPage();